<template>
  <div>
    <div>
      <Carousel
        containerHeight="550px"
        :carouselItems="topItems"
        @obj-detail="objDetail"
      />
    </div>
    <div class="container">
      <div>
        <el-row
          style="background-color: #FFFFFF;padding: 30px 0;border-radius: 5px;"
        >
          <el-row
            style="padding: 10px 5px;margin: 0 5px;box-sizing: border-box;"
          >
            <el-row>
              <span
                style="display: inline-block;font-size: 26px;font-weight: 800;padding-left: 15px;"
                >景点信息</span
              >
              <span style="float: right;">
                <el-select
                  @change="fetchFreshData"
                  size="small"
                  v-model="scenicQueryDto.categoryId"
                  style="margin-left: 5px;"
                  placeholder="所属类别"
                >
                  <el-option
                    v-for="item in categories"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
                <el-date-picker
                  size="small"
                  style="width: 220px;margin-left: 5px;"
                  v-model="searchTime"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="创建开始"
                  end-placeholder="创建结束"
                >
                </el-date-picker>
                <el-input
                  size="small"
                  style="width: 188px;margin-left: 5px;margin-right: 6px;"
                  v-model="scenicQueryDto.name"
                  placeholder="景点名"
                  clearable
                  @clear="handleFilterClear"
                >
                  <el-button
                    slot="append"
                    @click="handleFilter"
                    icon="el-icon-search"
                  ></el-button>
                </el-input>
              </span>
            </el-row>
          </el-row>
          <el-row
            style="margin: 0 15px;border-top: 1px solid rgb(245,245,245);"
          >
            <el-row v-if="tableData.length === 0">
              <el-empty description="暂无景点信息"></el-empty>
            </el-row>
            <el-row v-else class="scenic-grid">
              <el-col
                :xs="24"
                :sm="12"
                :md="8"
                :lg="6"
                v-for="(scenic, index) in tableData"
                :key="index"
                @click.native="scenicClick(scenic)"
              >
                <div class="scenic-card">
                  <div class="card-image">
                    <img :src="scenic.cover" :alt="scenic.name" />
                    <div class="image-overlay">
                      <span class="scenic-name">{{ scenic.name }}</span>
                      <span class="scenic-address">
                        <i class="el-icon-location"></i>
                        {{ scenic.address }}
                      </span>
                    </div>
                  </div>
                  <div class="card-footer">
                    <div class="meta-info">
                      <span class="time">{{ timeAgo(scenic) }}</span>
                      <span class="stats">
                        <span class="save"
                          >收藏{{ strDeal(scenic.saveIds) }}</span
                        >
                        <span class="view"
                          >浏览{{ strDeal(scenic.viewIds) }}</span
                        >
                      </span>
                    </div>
                    <div class="extra-info">
                      <span
                        ><i class="el-icon-school"></i
                        >{{ scenic.vendorName }}</span
                      >
                      <span class="area">{{ scenic.areaName }}</span>
                      <span class="category">{{ scenic.categoryName }}</span>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
            <el-pagination
              style="margin:10px 0;"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[8]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalItems"
            ></el-pagination>
          </el-row>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import Carousel from "@/components/Carousel";
import { timeAgo } from "@/utils/data";
export default {
  components: { Carousel },
  data() {
    return {
      topItems: [],
      tabsItem: [],
      data: {},
      filterText: "",
      currentPage: 1,
      pageSize: 8,
      totalItems: 0,
      tableData: [],
      scenicQueryDto: {}, // 搜索条件
      categories: [],
      searchTime: [],
      scenicTopList: []
    };
  },
  created() {
    this.fetchFreshData();
    this.fetchCategories();
    this.fetchScenicTop();
  },
  methods: {
    objDetail(obj) {
      const detail = this.scenicTopList.filter(entity => entity.id === obj.id);
      sessionStorage.setItem("scenicInfo", JSON.stringify(detail[0]));
      // 跳转至景点详情页
      this.$router.push("/scenicDetail");
    },
    tabChange(tab) {
      console.log(tab);
    },
    scenicClick(scenic) {
      sessionStorage.setItem("scenicInfo", JSON.stringify(scenic));
      // 跳转至景点详情页
      this.$router.push("/scenicDetail");
    },
    // 收藏与浏览的处理方法
    strDeal(str) {
      if (str === null) {
        return "(0)";
      }
      const saveIdsAry = str.split(",");
      return "(" + saveIdsAry.length + ")";
    },
    timeAgo(scenic) {
      return timeAgo(scenic.createTime);
    },
    // 查询推荐景点
    fetchScenicTop() {
      this.$axios
        .get(`/scenic/recommend/${3}`)
        .then(res => {
          if (res.data.code === 200) {
            this.scenicTopList = res.data.data;
            this.topItems = res.data.data.map(entity => {
              return {
                id: entity.id,
                subtitle: entity.categoryName,
                title: entity.name,
                image: entity.cover
              };
            });
          }
        })
        .catch(error => {
          console.error("查询推荐景点信息异常：", error);
        });
    },
    // 获取景点分类
    fetchCategories() {
      this.$axios
        .post("/scenicCategory/query", {})
        .then(res => {
          if (res.data.code === 200) {
            this.categories = res.data.data;
            this.categories.unshift({ id: null, name: "全部" });
            this.scenicQueryDto.categoryId = null;
            this.topItems = res.data.data.filter(entity => {
              return {
                label: entity.name,
                value: entity.id
              };
            });
          }
        })
        .catch(error => {
          console.error("查询景点分类信息异常：", error);
        });
    },
    async fetchFreshData() {
      try {
        this.tableData = [];
        let startTime = null;
        let endTime = null;

        if (this.searchTime != null && this.searchTime.length === 2) {
          const [startDate, endDate] = this.searchTime;

          // 设置开始时间为当天的 00:00:00
          startTime = new Date(startDate);
          startTime.setHours(0, 0, 0, 0);

          // 调整时区偏移
          const timeZoneOffset = startTime.getTimezoneOffset();
          startTime = new Date(
            startTime.getTime() - timeZoneOffset * 60 * 1000
          );

          // 设置结束时间为当天的 23:59:59
          endTime = new Date(endDate);
          endTime.setHours(23, 59, 59, 999);

          // 调整时区偏移
          endTime = new Date(endTime.getTime() - timeZoneOffset * 60 * 1000);

          // 将时间转换为 ISO 格式（如果需要）
          startTime = startTime.toISOString();
          endTime = endTime.toISOString();
        }
        // 请求参数
        const params = {
          current: this.currentPage,
          size: this.pageSize,
          key: this.filterText,
          startTime: startTime,
          endTime: endTime,
          ...this.scenicQueryDto
        };
        const response = await this.$axios.post("/scenic/query", params);
        const { data } = response;
        this.tableData = data.data;
        this.totalItems = data.total;
      } catch (error) {
        console.error("查询景点信息异常:", error);
      }
    },
    handleFilter() {
      this.currentPage = 1;
      this.fetchFreshData();
    },
    handleFilterClear() {
      this.filterText = "";
      this.handleFilter();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchFreshData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchFreshData();
    }
  }
};
</script>
<style scoped lang="scss">
.scenic-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10px;
  /* 补偿卡片间距 */

  .el-col {
    padding: 0 10px;
    margin-bottom: 20px;
    box-sizing: border-box;
  }
}

.scenic-card {
  height: 100%;
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  }

  .card-image {
    position: relative;
    height: 200px;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.5s;
    }

    &:hover img {
      transform: scale(1.05);
    }

    .image-overlay {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      padding: 15px;
      background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));

      .scenic-name {
        display: block;
        font-size: 18px;
        font-weight: 600;
        color: white;
        margin-bottom: 5px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .scenic-address {
        font-size: 12px;
        color: rgba(255, 255, 255, 0.9);

        i {
          margin-right: 5px;
        }
      }
    }
  }

  .card-footer {
    padding: 15px;

    .meta-info {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      font-size: 12px;
      color: #999;

      .stats {
        span {
          margin-left: 8px;

          &:first-child {
            margin-left: 0;
          }
        }
      }
    }

    .extra-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 12px;

      .category {
        padding: 3px 8px;
        border-radius: 4px;
        background-color: #f0f7ff;
        color: #409eff;
      }
      .area {
        margin-left: auto;
        padding: 3px 8px;
        border-radius: 4px;
        background-color: #f6effb;
        color: rgb(189, 109, 250);
      }
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .scenic-grid .el-col {
    flex: 0 0 50%;
    max-width: 50%;
  }
}

@media (max-width: 480px) {
  .scenic-grid .el-col {
    flex: 0 0 100%;
    max-width: 100%;
  }
}

.container {
  .left {
    width: 80%;
    padding: 30px 10px;
    box-sizing: border-box;
  }

  .right {
    width: 20%;
  }
}

.scenic-item {
  .item:hover {
    box-shadow: 0 8px 16px rgb(210, 208, 208);
  }

  .item {
    margin-block: 20px;
    padding: 20px 10px;
    border-radius: 6px;
    box-sizing: border-box;
    cursor: pointer;
    position: relative;
    border-radius: 20px;

    .extra-info {
      display: flex;
      justify-content: left;
      align-items: center;
      gap: 5px;
      font-size: 12px;

      span:last-child {
        display: inline-block;
        padding: 3px 6px;
        border-radius: 3px;
        background-color: aliceblue;
        color: rgb(84, 49, 223);
      }
    }

    img {
      width: 100%;
      height: 200px;
      border-radius: 20px;
    }

    .address {
      position: absolute;
      bottom: 80px;
      margin-right: 30px;
      right: 0;
      margin-top: 10px;
      color: rgb(255, 255, 255);
      font-weight: bold;
      display: inline-block;
      background-color: rgba(23, 23, 23, 0.4);
      padding: 4px 6px;
      font-size: 12px;
    }

    // .name {
    //     font-size: 20px;
    //     font-weight: 800;
    // }

    .name {
      position: absolute;
      top: 20px;
      padding: 10px;
      box-sizing: border-box;
      border-top-left-radius: 20px;
      // width: 140px;
      font-size: 22px;
      color: rgb(255, 255, 255);
      font-weight: bold;
      background-color: rgba(0, 0, 0, 0.3);
      border-bottom-right-radius: 20px;
      // white-space: nowrap;
      // overflow: hidden;
      // text-overflow: ellipsis;
    }

    .info {
      display: flex;
      justify-content: left;
      gap: 5px;
      margin-block: 6px;

      span {
        font-size: 12px;
      }
    }
  }
}
</style>
